export default {
  data () {
    return {
      grid: {
        // 是否在页面创建时执行
        created: true,
        // 查询url
        url: undefined,
        // 分页信息
        page: {
          // 第几页
          current: 1,
          // 条数统计
          total: 0,
          // 每页几条
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '40'],
          showSizeChanger: true,
          showTotal: this.pageShowTotal
        },
        // 表格数据
        data: [],
        // 查询参数
        query: {},
        // 表格加载状态
        load: false
      }
    }
  },
  methods: {
    // 重置查询参数
    queryReset () {
      this.grid.query = {}
    },
    // 点击查询按钮，重置分页信息查询
    searchQuery () {
      this.grid.page = {
        current: 1,
        total: 0,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40'],
        showSizeChanger: true,
        showTotal: this.pageShowTotal
      }
      this.getGridData()
    },
    // 点击分页器进行查询
    pageQuery (pagination) {
      this.grid.page = pagination
      this.getGridData()
    },
    // 查询参数转换钩子函数 ！！！必须返回！！！
    queryParamsTransForm (params) {
      return params
    },
    // 查询结果转换钩子函数 ！！！必须返回！！！
    queryDataTransForm (data) {
      return data
    },
    // 分页参数转换钩子函数 ！！！必须返回！！！
    queryPageTransForm (current, pageSize) {
      return { pageNum: current, pageSize }
    },
    // 分页器显示条数
    pageShowTotal (total) {
      return `共${total}条`
    },
    // 查询
    async getGridData () {
      if (!this.grid.url) {
        this.$message.newFun('未设置url', 'error', 3)
        return
      }
      this.grid.load = true

      const { current, pageSize } = this.grid.page
      const queryPage = this.queryPageTransForm(current, pageSize)
      const queryParams = this.queryParamsTransForm({ ...this.grid.query })
      const params = Object.assign({}, queryParams, queryPage)
      const res = await this.grid.url(params)
      const { isSuccess, data, msg } = res
      if (isSuccess) {
        let { records, current, total } = data
        if (records === null) { records = [] }
        this.grid.data = this.queryDataTransForm(records)
        Object.assign(this.grid.page, { current, total })
      } else {
        this.$message.newFun(msg, 'error', 3)
      }
      this.grid.load = false
    }
  },
  created () {
    if (this.grid.created) {
      this.queryReset()
      this.getGridData()
    }
  }
}
